
var CreateController = function($scope, $http, $upload){
	 $http.defaults.headers.post["Content-Type"] = "application/json";
     var urlBase="http://localhost:8080/finalproject";
     
     $scope.percent = '';
     
     $scope.dataUrls = [];
     
     $scope.onFileSelect = function($files){
    	 var $file = $files[0];
         if(window.FileReader && $file.type.indexOf('image') > -1){
                 var fileReader = new FileReader();
                 fileReader.readAsDataURL($file);
                 
                 fileReader.onload = function(e){
                         $scope.dataUrls['imagenew'] = e.target.result;
                 }
         }
         
         $scope.upload = $upload.upload({
                 url: urlBase + '/create/file/upload',
         }).progress(function(evt){
                 $scope.percent = parseInt(100.0 * evt.loaded / evt.total);
                  console.log('percent: ' +  $scope.percent);
         }).success(function(respone){
        	 console.log($scope.dataUrls['imagenew']);
        	 	$scope.sendToDatabase($scope.dataUrls['imagenew']);
                 console.log("upload finished");
         }).error(function(){
                 console.log("upload failed");
         });
         
         
     };
     
     $scope.sendToDatabase = function(dataUrlsN){
         $http.post(urlBase + '/create/file/image', dataUrlsN).success(function(respone){
                 $scope.dataUrls['image'] = respone;
         }).error(function(){
                 alert("failed");
         })
     }
     
     $scope.createUser = function(user){
    	 $scope.resetError();

    	 $http.post(urlBase + '/create/user', user).success(function(){
    		 $scope.setError("Create User successfully");
    	 }).error(function(){
    		 $scope.setError("Can't create User");
    	 });
     };
     
     $scope.setError = function(message){
         $scope.error = true;
         $scope.errorMessage = message;
	 }
	 
	 $scope.resetError = function(){
         $scope.error = false;
         $scope.errorMessage = '';
	 }
}